package utils

import (
  "bytes"
  "encoding/binary"
  "encoding/hex"
  "time"
)

func DecodeHex(src []byte) ([]byte, error) {
  dst := make([]byte, 64)
  n, err := hex.Decode(dst, src)
  return dst[:n], err
}

func GetTimeHex() []byte {
  now := time.Now()
  year, month, day := now.Date()
  hour, minute, second := now.Clock()

  hexYear := uint16(year)
  hexMonth := uint8(month)
  hexDay := uint8(day)
  hexHour := uint8(hour)
  hexMinute := uint8(minute)
  hexSecond := uint8(second)

  var buffer bytes.Buffer
  binary.Write(&buffer, binary.LittleEndian, hexYear)
  binary.Write(&buffer, binary.LittleEndian, hexMonth)
  binary.Write(&buffer, binary.LittleEndian, hexDay)
  binary.Write(&buffer, binary.LittleEndian, hexHour)
  binary.Write(&buffer, binary.LittleEndian, hexMinute)
  binary.Write(&buffer, binary.LittleEndian, hexSecond)

  hexBytes := buffer.Bytes()
  return hexBytes
}

func GetTimestampHex() []byte {
  now := int32(time.Now().Unix())

  var buffer bytes.Buffer
  binary.Write(&buffer, binary.LittleEndian, now)
  return buffer.Bytes()
}

func BytesToInt(data []byte) uint64 {

  var ret uint64
  if len(data) == 0 {
    return 0
  }
  if len(data) == 1 {
    return uint64(data[0])
  }
  if len(data) == 2 {
    ret = uint64(binary.LittleEndian.Uint16(data[0:2]))
  }
  if len(data) == 4 {
    ret = uint64(binary.LittleEndian.Uint32(data[0:4]))
  }
  if len(data) == 8 {
    ret = uint64(binary.LittleEndian.Uint32(data[0:8]))
  }
  return ret
}

/* 网络字节序转化为本机字节序 */
func NetToHostBytes(netData []byte, n int) []byte {

  if len(netData)%n != 0 || n == 1 {
    return netData
  }

  hostData := make([]byte, len(netData))

  for i := 0; i < len(netData); i += n {
    switch n {
    case 2:
      value := binary.BigEndian.Uint16(netData[i : i+2])
      binary.LittleEndian.PutUint16(hostData[i:i+2], value)
    case 4:
      value := binary.BigEndian.Uint32(netData[i : i+4])
      binary.LittleEndian.PutUint32(hostData[i:i+4], value)
    default:
      return netData
    }
  }

  return hostData
}
